// pages/cart/cart.js
const computedBehavior = require("miniprogram-computed").behavior;

Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    total: [],
    allCheck: false,
    checkedNum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const cartList = wx.getStorageSync("cartList");
    this.setData({ cartList });
  },
  onShow() {
    this.setBadge();
  },
  computed: {
    // 每一项商品的金额
    total({ cartList }) {
      let sumList = [];
      let sum = 0;
      cartList.forEach((item) => {
        sum = item.goods_price * item.goods_count;
        sumList.push(sum);
      });
      return sumList;
    },
    // 所有商品的金额
    allTotal({ cartList }) {
      let sum = 0;
      cartList.forEach((item) => {
        if (item.goods_state) {
          sum += item.goods_price * item.goods_count;
        }
      });
      return sum * 100;
    },
    // 全选
    allCheck({ cartList }) {
      let i = 0;
      cartList.map((v) => {
        return v.goods_state ? i++ : i;
      });
      if (i === cartList.length) {
        return true;
      } else {
        return false;
      }
    },
    // 选中的数量，用于购物车徽标
    checkedNum({ cartList }) {
      let j = 0;
      cartList.forEach((i) => {
        i.goods_state ? j++ : j;
      });
      return j;
    },
  },
  // 改变数量
  onChange({ detail, mark }) {
    this.data.cartList[mark.index].goods_count = detail;
    console.log(this.data.cartList[mark.index]);
    this.setData({ cartList: this.data.cartList });
    wx.setStorageSync("cartList", this.data.cartList);
  },
  //   单选框
  check({ mark }) {
    this.data.cartList[mark.index].goods_state =
      !this.data.cartList[mark.index].goods_state;
    this.setData({
      cartList: this.data.cartList,
    });
    wx.setStorageSync("cartList", this.data.cartList);
  },
  //   全选框
  allChecked() {
    this.setData({
      allCheck: !this.data.allCheck,
    });
    this.data.cartList.forEach((v) => {
      v.goods_state = this.data.allCheck;
    });
    this.setData({
      cartList: this.data.cartList,
    });
    wx.setStorageSync("cartList", this.data.cartList);
  },
  //   购物车徽标提示
  setBadge() {
    wx.setTabBarBadge({
      index: 2,
      text: this.data.checkedNum + "",
    });
  },
  watch: {
    checkedNum() {
      this.setBadge();
    },
  },
});
